package cn.itcast.hotel;

import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 创建一个线程
 * 通过对任务的执行
 * 演示线程池的运行原理
 **/
public class E1_线程池_线程池运行原理 {
    public static volatile boolean flag = true;
    public static void main(String[] args) {
        // 用于演示效果
        new Thread(()->{
            // 接收控制台参数
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()){
                String s = scanner.nextLine();
                // 如果控制输入stop 将flag设置false, 所有任务都会执行完毕
                if ("stop".equals(s)){
                    flag = false;
                    break;
                }
            }
        }).start();
        // 创建线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2,
                5,
                10,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy());
//        executor.allowCoreThreadTimeOut(true);
        for (int i = 0; i < 20; i++) {
            try {
                // 循环执行 20个任务
                executor.execute(new MyRunnable("第"+(i+1)+"号任务"));
            } catch (Throwable e) {
                e.printStackTrace();
                System.out.println("丢弃任务: " + (i+1) );
            }
        }

//        executor.shutdown();

//        List<Runnable> runnables = executor.shutdownNow();
    }
    static class MyRunnable implements Runnable{
        private String name;
        public MyRunnable(String name) {
            this.name = name;
        }
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() +"==>" +name);
            while (flag){  // true
                //flag是一个开关，为true时线程任务会一直执行让线程一直执行
            }
        }
    }
}